package com.fuhao.member.service;

import com.alibaba.fastjson.JSONObject;
import com.fuhao.core.Constants.Constants;
import com.fuhao.core.base.BaseApiService;
import com.fuhao.core.base.BaseResponse;
import com.fuhao.core.utils.BeanUtil;
import com.fuhao.core.utils.MD5Util;
import com.fuhao.dto.input.MemberInpDTO;
import com.fuhao.member.entity.MemberEntity;
import com.fuhao.member.feign.VerificaCodeServiceFeign;
import com.fuhao.member.mapper.UserMapper;
import com.fuhao.weixin.Service.VerificaCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhang
 * @title: 用户注册
 */
@RestController
public class MemberRegisterServiceImpl extends BaseApiService<JSONObject> implements MemberRegisterService {

    @Autowired
    private VerificaCodeServiceFeign verificaCodeServiceFeign;
    @Autowired
    private UserMapper userMapper;

    @Override
    public BaseResponse<JSONObject> register(@RequestBody MemberInpDTO memberInpDTO, String registCode) {
        String userName = memberInpDTO.getUserName();
        if(StringUtils.isEmpty(userName)){
            return setResultError("账号不能为空");
        }
        String password = memberInpDTO.getPassword();
        if(StringUtils.isEmpty(password)){
            return setResultError("密码不能为空");
        }
        String mobile = memberInpDTO.getMobile();
        if(StringUtils.isEmpty(mobile)){
            return setResultError("手机号不能为空");
        }
        //校验验证码
        BaseResponse<JSONObject> resultVerifica = verificaCodeServiceFeign.verificaWeixinCode(mobile, registCode);
        if(!Constants.HTTP_RES_CODE_200.equals(resultVerifica.getRtnCode())){
            return setResultError(resultVerifica.getMsg());
        }
        //加密
        String newPassword = MD5Util.MD5(password);
        memberInpDTO.setPassword(newPassword);
        //实体转换并保存到数据库
        MemberEntity memberEntity = BeanUtil.dtoToDo(memberInpDTO, MemberEntity.class);
        int row = userMapper.register(memberEntity);
        return row > 0 ? setResultSuccess("注册成功"):setResultError("注册失败");
    }
}
